package sw6.xmlvalidator.updater;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import sw6.xmlvalidator.definitions.Definitions;

/**
 * Checks the version of this tool by download a textfile
 * with latest version information. The downloaded version
 * number is returned s.t. it can be decided whether the
 * user should update this tool or not.
 * @author Lasse
 */
public class ProgramUpdater {

	public static double getLatestVersionNumber() {
		
		//Per default, the newest version is the current version
		double onlineVersion = Definitions.CURRENT_VERSION;
		
		//Print status
		System.out.print("Checking for newer version of this tool...");
		
		// Try to download a textfile from the net where the version
		// is written on the first line.
		try {
			// Create a new URL instance
			URL url 				= new URL(Definitions.URL_LATEST_VERSION);
			
			// Use for reading content of the downloaded file
			BufferedReader in 		= new BufferedReader(new InputStreamReader(url.openStream()));
			String latestVersion	= "";
			StringBuilder sb		= new StringBuilder();
			
			// Read all lines from the text file
			while ((latestVersion = in.readLine()) != null) {
				sb.append(latestVersion);
			}
			in.close();
			
			// Parse the online version
			onlineVersion 			= Double.parseDouble(sb.toString());
			
			System.out.println(" Done.");
		} catch (Exception e) {
			System.out.println(" Error.");
		}
		
		return onlineVersion;
	}
}
